/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.type;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 类型引用，主要是获取泛型
 * References a generic type.
 *
 * @param <T> the referenced type 泛型类型
 * @author Simone Tripodi
 * @since 3.1.0
 */
public abstract class TypeReference<T> {

    /**
     * TypeReference<T> 中T的泛型类型
     */
    private final Type rawType;

    protected TypeReference() {
        // 获取当前类的泛型类型
        rawType = getSuperclassTypeParameter(getClass());
    }

    Type getSuperclassTypeParameter(Class<?> clazz) {
        // 获取当前Class表示的实体的直接超类Type。
        Type genericSuperclass = clazz.getGenericSuperclass();
        if (genericSuperclass instanceof Class) {
            // 当前Class的超类还是Class类型的，递归处理.
            // try to climb up the hierarchy until meet something useful
            if (TypeReference.class != genericSuperclass) {
                // 递归
                return getSuperclassTypeParameter(clazz.getSuperclass());
            }

            throw new TypeException("'" + getClass() + "' extends TypeReference but misses the type parameter. "
                    + "Remove the extension or add a type parameter to it.");
        }

        // 获取超类的泛型参数的实际类型
        Type rawType = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        // TODO remove this when Reflector is fixed to return Types
        if (rawType instanceof ParameterizedType) {
            // 如果是参数化类型则继续获取其原始类型
            rawType = ((ParameterizedType) rawType).getRawType();
        }

        // 返回原始类型
        return rawType;
    }

    public final Type getRawType() {
        return rawType;
    }

    @Override
    public String toString() {
        return rawType.toString();
    }

}
